package com.eascs.banknet.boc.service.ftp;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.DataListDao;
import com.eascs.banknet.boc.dao.LoanapplyDao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.FtpFileTemplage;
import com.eascs.banknet.common.entity.DataListEntity;
import com.eascs.banknet.common.entity.LoanUserEntity;
import com.eascs.banknet.common.entity.LoanapplyEntity;
import com.eascs.banknet.constant.FileTypeConstants;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

/**
 * 中行ftp文件上传与下载服务
 * @author Administrator
 *
 */
public class BOCFtpUploadService extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOCFtpUploadService.class);
	@Autowired
	private LoanapplyDao loanapplyDao;
	@Autowired
	private DataListDao dataListDao;

	@Override
	public Map<String, String> dowork() {
		getAttachment();
		sendAttachment();
		return null;
	}
	
	/**
	 * 从中行FTP拉取征信报告，借款合同与借据等类型的附件
	 */
	private void getAttachment(){
		String loanapplyNo = "";
		String appno = "";
		try {
			logger.info("开始获取中行FTP文件...");
			List<LoanUserEntity> dataList = loanapplyDao.getLoanList();
			if(dataList.isEmpty()){
				logger.info("中行FTP下载， 没有符合条件的数据");
				return;
			}
			List<String> fileTypeList = Arrays.asList(FileTypeConstants.DALIST_TYPE_ZXBGDATA, FileTypeConstants.DALIST_TYPE_ZXMATE,
					FileTypeConstants.DALIST_TYPE_REFUNDCONTRACTBAK);
			for(LoanUserEntity loanUserEntity : dataList){
				loanapplyNo = loanUserEntity.getLoanapplyNo();
				LoanapplyEntity loanapplyEntity = loanapplyDao.getById(LoanapplyEntity.class, loanapplyNo);
				for(String fileType: fileTypeList){
					appno = loanUserEntity.getBankApplyno(); 
					FtpFileTemplage ftpFile = bocUtil.getBocFtpFileTemplate(fileType);
					//查询配偶bankApplyno，获取配偶征信报告
					if(FileTypeConstants.DALIST_TYPE_ZXMATE.equals(fileType)){
						String spouseId = loanUserEntity.getSpouseId();
						if(StringUtil.isEmpty(spouseId)){
							String sql = "select * from o2o_loan_user u where u.loanapply_no=? and u.spouse_id = ?";
							LoanUserEntity mateLoanUser  = loanapplyDao.findEntity(sql, LoanUserEntity.class, loanapplyNo, loanUserEntity.getLoanId());
							if(null == mateLoanUser){
								continue;
							}
							appno = mateLoanUser.getBankApplyno();
						}
					}
					//已签合同或者没有银行osn不需要拉取文件
					if(FileTypeConstants.DALIST_TYPE_REFUNDCONTRACTBAK.equals(fileType)){
						if(StringUtil.isEmpty(loanapplyEntity.getBankOsn())
								|| "Y".equals(loanapplyEntity.getContractFlag())){
							continue;
						} 
					}
					//检查文件是否已下载
					int count = dataListDao.getFileCount(loanapplyNo, ftpFile.getFileType());
					if(count > 0) {
						continue;
					}
					boolean saveResult = bocNetService.getFtpAttachment(ftpFile, appno, loanapplyNo, loanapplyEntity.getBankOsn());
					if(!saveResult){
						logger.error("文件下载失败， appno:[{}], loanapplyNo:[{}], fileType:[{}]", appno, loanapplyNo, fileType);
					}
				}
			}
			logger.info("获取中行FTP文件完成");
		} catch (Exception e) {
			logger.error("获取中行FTP文件出现异常， id:[{}], errMsg：[{}]", loanapplyNo, e);
		}
	}
	
	/**
	 * 向中行上传申报资料
	 */
	private void sendAttachment(){
		String appno = "";
		LogEntity logEntity = initLogData();
		logEntity.setTransType("FTP_BANKAPPLYDATA");
		logEntity.setTypeName("上传中行申报资料");
		try {
			logger.info("开始上传中行申报资料...");
			List<LoanUserEntity> dataList = loanapplyDao.getSendBankFtpApplyList();
			if(dataList.isEmpty()){
				logger.info("上传中行申报资料， 没有符合条件的数据");
				return;
			}
			for(LoanUserEntity entity:dataList){
				appno = entity.getBankApplyno();
				List<DataListEntity> fileList = dataListDao.getFileDataList(entity.getLoanapplyNo(), 
						Arrays.asList(FileTypeConstants.DALIST_TYPE_BANKAPPLYDATA));
				bocNetService.sendFtpAttachment(appno, fileList);
				logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_SUCCESS, null);
			}
			logger.info("上传中行申报资料完成");
		} catch (Exception e) {
			logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			logger.error("上传中行申报资料出现异常，appno:[{}], errMsg：[{}]", appno, e);
			e.printStackTrace();
		}
	}

	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("FTP_CREDIT");
		logEntity.setTypeName("中行FTP文件");
		logEntity.setStartTime(new Date());
		return logEntity;
	}

}
